package com.homework.search.controller;

import com.homework.common.resultVo.R;
import com.homework.search.client.HwSearchClient;
import com.homework.search.dto.SearchResultDTO;
import com.homework.search.model.PostDocument;
import com.homework.search.service.SearchService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/hw-search")
public class SearchController implements HwSearchClient {

    @Autowired
    SearchService searchService;

    /**
     * 搜索
     *
     * @param
     * @return
     */
    @RequestMapping("/search/{current}/{size}")
    public R<SearchResultDTO> search(@PathVariable("current") Integer current, @PathVariable("size") Integer size, String keyword) {

        // 分页参数，从零开始的，让首页从1开始
        Pageable pageable = PageRequest.of(current - 1, size);
        Page<PostDocument> results = searchService.query(pageable, keyword);

        SearchResultDTO page = new SearchResultDTO(current, size, results.getTotalElements());
        page.setRecords(results.getContent());

        return R.ok(page);
    }
}
